//
//  MultiPlayerViewController.m
//  CloudPlayerDemo
//
//  Created by Ru He on 2022/3/2.
//

#import "MultiPlayerViewController.h"
#import <HuaweiCloudPlayer/HuaweiCloudMultiPlayer.h>
#import "MultiPlayerView.h"

#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#define MARGIN 2

@interface MultiPlayerViewController ()<HuaweiCloudMultiPlayerDelegate>

@property (nonatomic, strong) HuaweiCloudMultiPlayer *multiPlayer;
@property (nonatomic, strong) NSMutableArray *playerViews;

@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIButton *play;

@end

@implementation MultiPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.restrictRotation = YES;
    [self setDeviceInterfaceOrientation:UIDeviceOrientationLandscapeRight];
    self.view.backgroundColor = [UIColor blackColor];
    self.playerViews = [NSMutableArray arrayWithCapacity:0];
    
    self.multiPlayer = [[HuaweiCloudMultiPlayer alloc] init];
    self.multiPlayer.delegate = self;
    
    __weak typeof(self) weakSelf = self;
    [self.dataArray enumerateObjectsUsingBlock:^(PlayerInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MultiPlayerView *playerView = [weakSelf createMultiPlayerView:obj];
        [weakSelf.view addSubview:playerView];
        [weakSelf.playerViews addObject:playerView];
        // 设置第一个机位为主机位
        if (idx == 0) {
            [weakSelf.multiPlayer setBaseDisplay:playerView.playerId];
        }
    }];
    
    [self updatePlayerViewConstraints];
    [self createOtherViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
}

- (MultiPlayerView *)createMultiPlayerView:(PlayerInfo *)info {
    MultiPlayerView *view = [[MultiPlayerView alloc] init];
    
    int playerId = [self.multiPlayer addDisplay:info.mediaUrl frame:view.bounds];
    view.playerId = playerId;
    UIView *playerView = [self.multiPlayer getPlayerView:playerId];
    [view insertSubview:playerView atIndex:0];
    
    return view;
}

- (void)updatePlayerViewConstraints {
    double smallViewHeight = (SCREENHEIGHT - 4*MARGIN)/3;
    double smallViewWidth = smallViewHeight*16/9;
    
    double largeViewHeight = SCREENHEIGHT - 2*MARGIN;
    double largeViewWidth = SCREENWIDTH - 3*MARGIN - smallViewWidth;
    
    double smallViewX = SCREENWIDTH - MARGIN - smallViewWidth;
    
    [self.playerViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MultiPlayerView *view = (MultiPlayerView *)obj;
        if (idx == 0) {
            view.frame = CGRectMake(MARGIN, MARGIN, largeViewWidth, largeViewHeight);
        } else {
            view.frame = CGRectMake(smallViewX, idx * MARGIN + (idx-1)*smallViewHeight, smallViewWidth, smallViewHeight);
        }
        UIView *playerView = [self.multiPlayer getPlayerView:view.playerId];
        playerView.frame = view.bounds;
        view.indicatorView.frame = CGRectMake(view.frame.size.width/2-2.5, view.frame.size.height/2-2.5, 5, 5);
    }];
}

- (void)createOtherViews {
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(40, 30, 40, 40);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(pushBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];

    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(80, SCREENHEIGHT - 70, SCREENWIDTH - 120, 20)];
    self.slider.userInteractionEnabled = NO;
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 200;
    self.slider.continuous = NO;
    self.slider.minimumTrackTintColor = [UIColor blueColor];
    self.slider.maximumTrackTintColor = [UIColor grayColor];
    [self.slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.slider.frame) - 150, CGRectGetMaxY(self.slider.frame), 150, 30)];
    self.timeLabel.backgroundColor = [UIColor clearColor];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:self.timeLabel];
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    self.play.frame = CGRectMake(40, SCREENHEIGHT - 75, 30, 30);
    [self.play setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    [self.play addTarget:self action:@selector(PlayOrPause:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.play];

}

- (void)pushBack:(UIButton *)back {
    
    if (self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    [self.multiPlayer stop];
    [self.multiPlayer destory];
    self.multiPlayer.delegate = nil;
    self.multiPlayer = nil;
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)PlayOrPause:(UIButton *)btn {
    if (self.dataArray[0].mediaType == MEDIA_TYPE_VOD) {
        if (self.multiPlayer.playing) {
            [self.multiPlayer pause];
            [self.play setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        } else {
            [self.multiPlayer start];
            [self.play setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        }
    }
}

- (void)sliderValueChanged:(UISlider *)slider {
    [self.multiPlayer seek:(slider.value*1000)];
}

- (void)willResignActive:(NSNotification *)notic {
    [self.multiPlayer pause];
}

- (void)didBecomeActive:(NSNotification *)notic {
    [self.multiPlayer start];
}

#pragma mark - HuaweiCloudMultiPlayerDelegate -
- (void)onPrepared:(HuaweiCloudMultiPlayer *)player playerId:(int)playerId {
    if (MEDIA_TYPE_VOD == self.dataArray[0].mediaType) {
        self.slider.userInteractionEnabled = YES;
        self.slider.maximumValue = player.duration/1000;
        
        if (!self.timer) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
                if (!self.slider.tracking) {
                    self.slider.value = player.currentPosition/1000;
                }
                
                int iMin = (int)(round(player.currentPosition/1000) / 60.0);
                int iSec = (int)round(player.currentPosition/1000) % 60;
                
                if (iMin < 0) {
                    iMin = 0;
                }
                
                if (iSec < 0) {
                    iSec = 0;
                }
                
                if (!isnan(player.duration)) {
                    self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d | %02d:%02d", iMin, iSec, (int)((player.duration/1000) / 60), (int)(player.duration/1000) % 60];
                }
            }];
        }
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)onBufferingUpdate:(HuaweiCloudMultiPlayer *)player percent:(int)percent playerId:(int)playerId {
    __weak typeof(self) weakSelf = self;
    [self.playerViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MultiPlayerView *playerView = weakSelf.playerViews[idx];
        if (playerView.playerId == playerId) {
            if (percent != 100) {
                playerView.indicatorView.hidden = NO;
                [playerView.indicatorView startAnimating];
            } else {
                playerView.indicatorView.hidden = YES;
                [playerView.indicatorView stopAnimating];
            }
            *stop = YES;
        }
    }];
}

- (void)onCompletion:(HuaweiCloudMultiPlayer *)player playerId:(int)playerId{

}

- (void)onError:(HuaweiCloudMultiPlayer *)player code:(int)code description:(NSString *)description playerId:(int)playerId{
    NSString *message = [NSString stringWithFormat:@"%@(%d),playerId:%d", description, code, playerId];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误信息" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}


@end
